import os
import platform
import subprocess

import flet as ft
import requests
from flet_core import UserControl, MainAxisAlignment, CrossAxisAlignment
import pyautogui


class PostItemLayout(UserControl):

    def __init__(self, page: ft.Page, user_info, download_dir, is_show_download_mask):
        super().__init__()
        self.download_mask = None
        self.downloading_mask = None
        self.downloaded_mask = None
        self.page = page
        screen_width, screen_height = pyautogui.size()
        self.screen_width = screen_width
        self.screen_height = screen_height
        self.item_width = self.screen_width * 0.75 / 6
        self.item_height = self.screen_width * 0.75 / 6 / 0.78
        self.download_dir = download_dir
        self.is_show_download_mask = is_show_download_mask
        self.visible_index = 0
        self.user_info = user_info

    def build(self):
        IMAGES_DIR = os.path.dirname(__file__)
        images_dir = os.path.join(IMAGES_DIR, "images")
        download_images = os.path.join(images_dir, "download.png")
        self.download_mask = ft.Container(
            expand=True,
            bgcolor="#80000000",
            content=ft.Column(
                controls=[
                    ft.Image(src=f"{download_images}", width=self.item_width * 0.2, height=self.item_width * 0.2, ),
                    ft.Text("点击下载", size=self.item_width * 0.1, text_align=ft.TextAlign.CENTER, color="#FFFFFF",
                            weight=ft.FontWeight.BOLD, ),
                ],
                alignment=MainAxisAlignment.CENTER,
                horizontal_alignment=CrossAxisAlignment.CENTER,
            ),
            alignment=ft.alignment.center,
            padding=0,
        )

        self.downloading_mask = ft.Container(
            expand=True,
            bgcolor="#80000000",
            content=ft.Column(
                controls=[
                    ft.Image(src=f"{download_images}", width=self.item_width * 0.2, height=self.item_width * 0.2, ),
                    ft.Text("下载中...", size=self.item_width * 0.1, text_align=ft.TextAlign.CENTER, color="#FFFFFF",
                            weight=ft.FontWeight.BOLD, ),
                ],
                alignment=MainAxisAlignment.CENTER,
                horizontal_alignment=CrossAxisAlignment.CENTER,
            ),
            alignment=ft.alignment.center,
            padding=0,
        )
        open_folder_text = ft.Text("点击查看文件", size=self.item_width * 0.1, text_align=ft.TextAlign.CENTER,
                                   color="#FFFFFF",
                                   weight=ft.FontWeight.BOLD, )
        self.downloaded_mask = ft.Container(
            expand=True,
            bgcolor="#80000000",
            content=ft.Column(
                controls=[
                    ft.Image(src=f"{download_images}", width=self.item_width * 0.2, height=self.item_width * 0.2, ),
                    ft.Text("已下载", size=self.item_width * 0.1, text_align=ft.TextAlign.CENTER, color="#FFFFFF",
                            weight=ft.FontWeight.BOLD, ),
                    open_folder_text,
                ],
                alignment=MainAxisAlignment.CENTER,
                horizontal_alignment=CrossAxisAlignment.CENTER,
            ),
            alignment=ft.alignment.center,
            padding=0,
        )

        self.download_mask.visible = False
        self.downloading_mask.visible = False
        self.downloaded_mask.visible = False
        if self.user_info.get("is_download") == 2:
            self.downloaded_mask.visible = True

        return ft.Container(
            expand=True,
            width=self.item_width,
            height=self.item_height,
            content=ft.Stack(
                controls=[
                    ft.Image(
                        width=self.item_width,
                        height=self.item_height,
                        src=f'{self.user_info["cover"]}',
                        expand=True,
                        fit=ft.ImageFit.FILL,
                        repeat=ft.ImageRepeat.NO_REPEAT,
                    ),
                    ft.Container(
                        content=ft.Text(self.user_info["create_at"], color="#FFFFFF", size=self.item_width * 0.07, ),
                        padding=5,
                        border_radius=ft.border_radius.only(10, 0, 0, 10, ),
                    ),
                    ft.Container(
                        content=ft.Container(
                            padding=8,
                            bgcolor='#80000000',
                            width=self.item_width,
                            height=self.item_width * 0.28,
                            content=ft.Text(f'{self.user_info["title"]}', max_lines=2, color='#FFFFFF',
                                            size=self.item_width * 0.07, ),
                        ),
                        alignment=ft.alignment.bottom_left
                    ),
                    self.download_mask,
                    self.downloading_mask,
                    self.downloaded_mask,
                ],
            ),
            ink=True,
            data=self.user_info,
            on_click=self.click_post_item,
            on_hover=self.hover_post_item,
        )

    def update_state(self):
        if self.user_info.get("is_download") == 0:
            if self.is_show_download_mask:
                self.visible_index += 1
                self.download_mask.visible = self.visible_index % 2 != 0
                self.update()
        elif self.user_info.get("is_download") == 1:
            self.download_mask.visible = False
            self.downloading_mask.visible = True
            self.update()
        else:
            self.downloading_mask.visible = False
            self.downloaded_mask.visible = True
            self.update()

    def hover_post_item(self, event):
        self.update_state()

    def click_post_item(self, event):
        download_base_dir = os.path.join(self.download_dir, self.user_info.get("author"))
        if not os.path.exists(download_base_dir):
            os.makedirs(download_base_dir)

        if self.user_info.get("is_download") == 0:
            self.user_info["is_download"] = 1
            self.update_state()

            dist_file_name = download_base_dir + "/" + self.user_info.get("title") + ".mp4"
            if not os.path.exists(dist_file_name):
                res = requests.get(self.user_info.get("download_url"), stream=True)
                with open(r'' + dist_file_name, "wb") as video_file:
                    for chunk in res.iter_content(chunk_size=10 * 1024):
                        if chunk:
                            video_file.write(chunk)
                self.user_info["is_download"] = 2
                self.user_info["is_download"] = 2
                self.update_state()

        elif self.user_info.get("is_download") == 2:
            if platform.system() == "Darwin":
                subprocess.call(['open', download_base_dir])
            elif platform.system() == "Windows":
                os.startfile(download_base_dir)
